/**
 * 
 */

package com.chengyu.eyc.utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import com.chengyu.eyc.exception.GenericException;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
public final class EycFileUtil extends cn.hutool.core.io.FileUtil {

    private static final String CACHE_CONTROL = "Cache-Control";

    private static final String CONTENT_DISPOSITION = "Content-Disposition";

    private static final String EXPIRES = "Expires";

    private static final String PRAGMA = "Pragma";

    /**
     * 文件名转码
     * 
     * @return
     */
    public static String encodeFileName(String fileName) {
        try {
            // encode编码UTF-8 解决大多数中文乱码
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            log.error("文件名转码失败", e);
        }
        fileName = fileName.replace("+", "%20");// encode后替换空格 解决空格问题
        return fileName;
    }

    private static String getExtensionNme(String fileName) {
        return StringUtils.isNotEmpty(fileName) ? fileName.substring(fileName.lastIndexOf('.') + 1) : null;
    }

    /**
     * @param fileName
     * @return
     */
    private static HttpHeaders getHttpHeaders(String fileName) {
        HttpHeaders headers = new HttpHeaders();// 设置一个head
        headers.add(CACHE_CONTROL, "no-cache, no-store, must-revalidate");
        headers.add(CONTENT_DISPOSITION, "attachment; filename=" + encodeFileName(fileName));
        headers.add(PRAGMA, "no-cache");
        headers.add(EXPIRES, "0");
        return headers;
    }

    /**
     * 下载文件
     * 
     * @return
     */
    public static ResponseEntity<FileSystemResource> getResponseResource(File file) {
        if (!file.exists()) {
            return null;
        }
        if (file.getPath().contains("..")) {
            throw new GenericException("路径错误");
        }
        HttpHeaders headers = getHttpHeaders(file.getName());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
    }


    public static String uploadFile(String path, MultipartFile multipartFile) throws IOException {
        String newFileName = null;
        if (!multipartFile.isEmpty()) {
            String fileName = multipartFile.getOriginalFilename();
            String fileType = getExtensionNme(fileName);

            String practicalFileType = FileTypeUtil.getType(multipartFile.getInputStream());
            if (!StrUtil.equals(fileType, practicalFileType)) {
                throw new GenericException("上载的文件不合法，请重新选择");
            }
            newFileName = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + StringUtils.leftPad(String.valueOf(RandomUtils.nextInt(0, 1000)), 2, "0") + "." + fileType;
            FileUtils.forceMkdir(new File(path));
            log.info("上传文件的路径:{},名称:{}", path, newFileName);
            File file = new File(path, newFileName);
            multipartFile.transferTo(file);

        }
        return newFileName;
    }

    private EycFileUtil() {

    }

}
